<template>
  <div class="public">
    <!--    后端为活动分配一个id-->
    <!-- <div class="h2">
      <h2>发布新活动</h2>
      <div class="line"></div>
    </div> -->

      <!-- <mt-field label="名称" placeholder="请输入活动的主题" v-model="title"></mt-field>
      <div class="pic">
        <input type="file" name="uploadFile" id="up-load-file" ref="upload" placeholder="">
        <label for="up-load-file" class="input-label" v-show="preview == ''">添加图片</label>
        <img :src="preview" alt="" ref="previewImg" v-show="preview != ''" @click="clearImage">
      </div>
         <mt-field label="类型" placeholder="请输入活动的类型" type="email" v-model="email"></mt-field>
      <div class="h2"></div>
      <mt-radio
          v-model="tag"
          :options=  "['聚餐：大家一起吃饭', '聚会：线下聚一聚', '学习：相互勉励，砥砺前行', '其他类型的活动']"
          align="left"
      >
      </mt-radio>
      <br>
      <mt-field label="联系方式" placeholder="方便参与者联系你" type="text" v-model="contact"></mt-field>
      <mt-field label="人数" placeholder="设置人数上限" type="text" v-model="maxNum"></mt-field>
      <mt-field label="结束时间" type="date" v-model="endTime"></mt-field>
      <mt-field label="简介" placeholder="介绍活动的时间地点以及各种相关信息" type="textarea" rows="4" v-model="introduce"></mt-field>
       -->
      

      <el-form ref="form" :model="form" label-width="5rem" style="text-align:left;">
        <div class="pic">
          <input type="file" name="uploadFile" id="up-load-file" ref="upload" placeholder="" >
          <label for="up-load-file" class="input-label" v-show="preview == ''">添加图片</label>
          <img :src="preview" alt="" ref="previewImg" v-show="preview != ''" @click="clearImage">
      </div>  
        
        <el-form-item label="活动名称" style="width:70vw;">
          <el-input v-model="form.title"></el-input>
        </el-form-item>
        
        <el-form-item label="联系电话">
          <el-input v-model="form.contact" style="width: 65vw"></el-input>
        </el-form-item>
        
        <el-form-item label="活动地点">
          <el-input v-model="form.location" style="width: 70vw"></el-input>
        </el-form-item>


        <el-form-item label="活动时间">
          <el-col :span="11">
            <el-date-picker type="date" placeholder="开始日期" v-model="form.beginTime" style="width: 90%;"></el-date-picker>
          </el-col>
          <el-col class="line" :span="1">-</el-col>
          <el-col :span="11">
            <el-date-picker type="date" placeholder="结束日期" v-model="form.endTime" style="width: 90%;"></el-date-picker>
          </el-col>
        </el-form-item>
        
        
        <el-form-item label="人数上限">
          <el-input-number v-model="form.maxNum" style="width:50%;" :min="2" :max="9999"></el-input-number>
        </el-form-item>
       
        <el-form-item label="活动类型">
          <el-radio-group v-model="form.tag" >
            <el-radio label="聚餐"></el-radio>
            <el-radio label="学习"></el-radio>
            <el-radio label="出游"></el-radio>
            <el-radio label="其他"></el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="活动简介">
          <el-input type="textarea" v-model="form.introduce" style="width:95%;" placeholder="上限250字"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm"  class="create-btn">立即创建</el-button>
        </el-form-item>
    </el-form>
    
    <br>
    <!-- <button class="public-btn" @click="pub">确认发布</button> -->
    <br><br>
<!--    <div>123</div>-->
  </div>
</template>

<script>
import {Field, MessageBox, Radio} from 'mint-ui';
import token from '@/apis/refresh_token'
import cosOps from '@/tools/cosOps'


export default {
  name: "Public",
  data() {
    return {
      // title:'',
      // tag: '',
      // contact: '',
      // introduce: '没有什么可以描述的简单活动~',
      // maxNum: '',
      // // beginTime: '',
      // endTime: '',
      publicMutexLock: false,
      // options: [
      //   {lable: '聚餐：大家一起吃饭',     value: '聚餐'},
      //   {lable: '聚会：线下聚一聚',       value: '聚会'},
      //   {lable: '学习：相互勉励，砥砺前行', value: '学习'},
      //   {lable: '其他类型的活动',         value: '其他'}
      // ],
      preview: '',
      form: {
        title: '',
        location: '',
        beginTime: '',
        endTime: '',
        maxNum: 10,
        tag: '聚餐',
        introduce: '',
        img: '',
        contact: ''
      },
      isLoading: false,
    }
  },
  components: {
    'mt-field': Field,
    'mt-radio': Radio
  },
  methods: {
    checkForm () {
      return this.form.endTime >= this.form.beginTime
          && this.form.title.trim('') && this.form.title.length < 25
          && this.form.contact.trim('') && this.form.title.length < 25
          && this.form.introduce.length < 250
          && this.form.img
      
    },
    // pub () {
    //   console.log(this.title)
    //   let imgFile = this.$refs.upload.files[0]
    //   let formatFile = new FormData().append("file", imgFile)
    //   console.log(formatFile)
    //   if(!(this.title && this.tag && this.contact && this.maxNum)) {
    //     MessageBox('没有填写必要的信息！', '填写活动名称/类型标签/人数上限后重试')
    //     return
    //   }
      
    //   console.log(this.title, this.tag, this.contact, this.maxNum)
    //   if(!this.publicMutexLock) {
    //     this.publicMutexLock = true
    //     // console.log(this.$refs.upload.files[0])
    //     // this.$axios.post('/back/user/fileUpload', {
    //     //   'upLoadFile': this.$refs.upload.files[0]
    //     //   // this.preview
    //     // }).then((res) => {
    //     //   console.log('图片上传成功', res.data)
    //     // }).catch((err) => {
    //     //   console.warn('图片上传失败', err)
    //     // })
    //     let timeArray = this.endTime.split('/')
    //     timeArray.join('-')
    //     timeArray += ' 24:00:00'
        
    //     let params = new FormData ()
    //     params.append('image', imgFile)
    //     params.append('title', this.title)
    //     params.append('tag', this.tag)
    //     params.append('introduce', this.introduce)
    //     params.append('maxNum', this.maxNum)
    //     params.append('endTime', timeArray)
    //     params.append('contact', this.contact)

    //     this.$axios.post('/back/active/addActive', 
    //       params,
    //       {
    //         headers: {
    //           'Content-Type':'application/x-www-form-urlencoded;multipart/form-data'
    //         }
    //       }
    //       ).then((res) => {
    //       console.log(res.data)
    //       MessageBox('活动发布成功','请返回首页查看')
    //       this.$router.replace('/')
    //       location.reload()
    //       // location.reload()
    //     }).catch((err) => {
    //       console.warn('活动发布失败',err)
    //       MessageBox('活动发布失败','请尝试重新发布', err)
    //       this.$router.replace('/')
    //     })

    //     let timeID = setTimeout(() => {
    //       this.publicMutexLock = false
    //       clearTimeout(timeID)
    //     }, 1200)

    //   } else {
    //     MessageBox('提示','提交过于频繁')
    //   }
    // },
    
    // 
    
    
    
    // 
    publish (callback) { // 不要直接调用这个函数，因为要做token认证，放到下面的submitForm里面
      let that = this
      this.$axios.post('/back/activity/publish', that.form, {
        headers: {
          'token': localStorage.getItem('token')
        }
      }).then((res) => {
        console.log('表单提交成功', res.data)
        if (callback) {
          callback (res.data.code)
        }
      }).catch((err) => {
        console.warn('提交失败', err)
      })
    },
    
    submitForm () {
      if (!this.checkForm()) {
        this.$message({
          message: '发布失败,请检查活动信息是否完整且有效',
          type: 'error'
        })
        return
      }
      let that = this
      token.request().then((res)=>{
        // console.log(res)
          that.publish(function (code) {
            if (code == 200) {
              that.$message({
                message: '发布成功',
                type: 'success'
              }),
              location.reload()
            } else {
              that.$message({
                message: '发布失败,请保证信息完整且有效',
                type: 'error'
              })
            }
          })  
        
      })
    },


    setImage () {
      let input = this.$refs.upload
      let that = this

      if (that.isLoading) {
        this.$message({
          message: '加载中，请勿频繁操作',
          type: 'warning'
        })
        return
      }
      input.addEventListener('input', () => {
        let file = input.files[0]
        
        let imageSize = (file.size * 3 / 4 / 1024 / 1024 * 2).toFixed(1) // 单位转为MB,当然有一定的误差，误差为+-0.5MB
        if((file.type).indexOf("image/")==-1) {
            this.$message({
              message: "上传失败，请上传图片类型文件",
              type: "error"
            })
            return 
        } else if(imageSize > 2.5) {
            this.$message({
              message: "图片过大，上传失败",
              type: 'error'
            })
            return 
        } else {
          that.isLoading = true
          
          cosOps.upload (file, function (data) {
              that.form.img = 'https://' + data.Location
              that.isLoading = false
              that.$message({
                message: '图片上传成功,再次点击可取消并重新上传',
                type: 'success'
              })
            }
          )
        }
        const fileReader = new FileReader()
        fileReader.readAsDataURL(file)
        // console.log(file, preview)
        fileReader.onload = function (e) {
          that.preview = this.result
        }
      })
    },
    clearImage () {
      this.preview = ''
    }
  },
  mounted () {
    // token.request ()
    this.setImage()
  
  }
}
</script>

<style scoped>
  .public{
    font-family: Helvetica, Arial, sans-serif !important;
    overflow: scroll;
    width: 100vw;
    height: 100vh;
    /*background: linear-gradient(45deg, #e8ecef, #d2cccc, #ffffff);*/
    background-color: #FFF;
  }
  /* .h2{
    width: 8rem;
    color: #000;
    text-align: left;
    margin: 20px 0 20px 0;
    text-align: center;
  } */
  /* h2{
    display: inline-block;
    font-size: 18px;
  } */
  /* .line{
    margin: 0 auto;
    width: 65%;
    height: 4px;
    background-color: #ff8800;
  } */
  
  /*.mint-cell-wrapper{*/
  /*  background-color: rgba(255, 255, 255, 0.1);*/
  /*}*/
  

  
  .public-btn{
    width: 50%;
    padding: 10px;

    /*border: 4px solid rgba(255,255,255,0.1);*/
    border: 4px solid rgba(255,135,0,0.1);

    border-radius: 10px;

    background-color: rgba(255,255,255,0.1);
    background-color: #ff8800;

    /*box-shadow: 2px 2px 20px rgba(255,255,255,0.2);*/
    box-shadow: 2px 2px 15px #ff8800;

    color: #fff;
    font-size: 18px;
  }
  .pic {
    width: 100vw;
    height: 16rem;
    /* background: #ff8800; */
    text-align: left;
    display: flex;
    background: #ff8800;
    margin: 0 0 2rem 0;
  }
  
  #up-load-file {
    /* display: block;
    background-color: purple !important;
    border: 1px solid #e3e3e3 !important;
    height: 5rem;
    width: 5rem; */
    display: none;
  }
  .pic img,
  label.input-label {
    
    display: block;
    height: 100%;
    width: 100%;
    border: 1px solid #e3e3e3;
    text-align: center;
    line-height: 16rem;
    background: #fff;
    font-size: 1.5rem;
  }
  
  input#file-upload-button {
    background-color: transparent !important;
    border: none;
  }
  
  .create-btn {
    /* width: 25vw;
    margin: 0 20vw; */
  }
</style>